package com.jied.duodian.config;

import com.jied.duodian.util.SuId;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * Description:
 *
 * @author LiJie
 * @date Created on 2020/11/8
 * WWW https://github.com/j6l
 */
@Component
@Slf4j
public class MinioHelper {

    @Autowired
    SuId suId;

    @Value(value = "${minio.bucket}")
    private String bucket;

    @Value(value = "${minio.host}")
    private String host;

    @Value(value = "${minio.url}")
    private String url;

    @Value(value = "${minio.access-key}")
    private String accessKey;

    @Value(value = "${minio.secret-key}")
    private String secretKey;

    public String putObject(MultipartFile multipartFile) throws InvalidEndpointException, InvalidPortException,
            IOException, InvalidKeyException, ErrorResponseException, IllegalArgumentException,
            InsufficientDataException, InternalException, InvalidBucketNameException, InvalidResponseException,
            NoSuchAlgorithmException, XmlParserException, RegionConflictException {
        MinioClient minioClient = new MinioClient( this.host, this.accessKey, this.secretKey );

        // bucket 不存在，创建
        if (!minioClient.bucketExists( this.bucket )) {
            minioClient.makeBucket( this.bucket );
        }
        try (InputStream inputStream = multipartFile.getInputStream()) {

            // 上传文件的名称
            String fileName = multipartFile.getOriginalFilename();
            fileName = getNewFileName( fileName );
            log.info( "上传了文件{}", fileName );

            // PutObjectOptions，上传配置(文件大小，内存中文件分片大小)
            PutObjectOptions putObjectOptions = new PutObjectOptions( multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE );
            // 文件的ContentType
            putObjectOptions.setContentType( multipartFile.getContentType() );
            minioClient.putObject( this.bucket, fileName, inputStream, putObjectOptions );

            // 返回访问路径
            return this.url + UriUtils.encode( fileName, StandardCharsets.UTF_8 );
        }
    }

    public String getNewFileName(String fileName) {
        int index = fileName.lastIndexOf( "." );
        String newFileName = suId.getuuid().replace( "-", "" ).toUpperCase();
        ;
        if (index != -1) {
            newFileName = newFileName + fileName.substring( index );
        }
        return newFileName;
    }
}
